/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package boundary;

import entity.Group;
import entity.User;
import entity.User_;
import java.io.Serializable;
import java.security.Principal;
import java.util.List;
import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;

/**
 *
 * @author andrea
 */
@Stateless
public class UserManager  implements Serializable{

    @PersistenceContext
    private EntityManager em;
    
    @Inject
    Principal principal;

    public void save(User user) {
        user.setGroupName(Group.USER);
        user.setPublicCalendar(false);
        em.persist(user);
    }

    public void unregister() {
        em.remove(getLoggedUser());
    }

    public User getLoggedUser() {
        return em.find(User.class, principal.getName());
    }
    
    public List<User> findPublicUser(){
        CriteriaBuilder cb= em.getCriteriaBuilder();
        CriteriaQuery<User> cq = cb.createQuery(User.class);
        
        Root<User> root = cq.from(User.class);
        
        cq.select(cq.from(User.class));
        cq.where(cb.isTrue(root.get(User_.publicCalendar)));

                
        return em.createQuery(cq).getResultList();    
    }
    
}
